import type { Router } from "vue-router";
import { useUserStore } from "@/stores";

// 白名单路由
const whiteList = ["/sign/login", "/sign/register", "/sign/forgot-password"];

export function setupRouterGuard(router: Router) {
	router.beforeEach(async (to, _from, next) => {
		const userStore = useUserStore();

		// 判断用户是否已登录
		if (userStore.isLoggedIn) {
			if (to.path === "/sign/login") {
				// 如果已登录且要跳转的页面是登录页，则跳转到首页
				next({ path: "/" });
			} else {
				next();
			}
		} else {
			// 未登录
			if (whiteList.includes(to.path)) {
				// 如果是白名单页面，直接进入
				next();
			} else {
				// 否则跳转到登录页面，并记录要跳转的页面路径
				next({
					path: "/sign/login",
					query: {
						redirect: to.fullPath,
					},
				});
			}
		}
	});
}
